import 'package:flutter/widgets.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/jzx_models.dart';
import 'package:hockey/services/jzx_config.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/dialogs/jzx_photo_sheet.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class JzxPublishPostController extends GetxController {
  var contentlength = 0.obs;
  final content = TextEditingController();
  final title = TextEditingController();

  final maxCount = 6;
  final images = <AssetEntity>[].obs;

  @override
  void onInit() {
    super.onInit();
    content.addListener(() {
      contentlength.value = content.text.length;
    });
  }

  /// 发布帖子
  void submitPost() async {
    // if (content.text.isEmpty && images.isEmpty && title.text.isEmpty) {
    //   showMessage('Images and labels are required！');
    //   return;
    // }

    try {
      showLoading();

      var temp = <String>[];

      for (var item in images) {
        final file = (await item.file);
        final path = await saveFile(file!);
        temp.add(path);
      }

      final item = JzxMediaData(
        title: title.text,
        content: content.text,
        cover: temp.removeAt(0),
        url: temp.join(','),
        // images: images.map((e) => e.fileUrl).toList(),
        id: JzxConfigService.to.postList.length + 11000,
        author: JzxUserService.to.author,
        // bindingUser: JzxUserService.to.uid,
        user: JzxUserService.to.authorData,
      );

      JzxConfigService.to.updatePostList(item);
      hideLoading();

      images.clear();
      content.clear();
      title.clear();

      showMessage('Successfully');
    } catch (e) {
      // log('$e');
    }
  }

  void pickerImages(BuildContext context) async {
    final res = await JzxPhotoSheet.show(
      context,
      maxAssets: maxCount - images.length,
    );

    if (res?.isNotEmpty == true) {
      showLoading();
      images.addAll(res!);
      hideLoading();

      // for (var item in res!) {
      // final file = await item.file;
      // }
    }
  }

  void removeImage(int i) {
    images.removeAt(i);
  }
}
